﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.ESS.APP.App_UI.Forms;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;
using _WebShared.Classes;

namespace KPIS.GERP.ESS.APP.App_UI.UserControls
{
    public partial class Mail_IcmPrePurchaseRequest : System.Web.UI.UserControl
    {
        Main main = new Main();
        IcmPrePurchaseRequestBLL pprBLL = new IcmPrePurchaseRequestBLL();
        B_HrmEmployees emplist = new B_HrmEmployees();
        B_MessageSend send = new B_MessageSend();
        B_MessageReply reply = new B_MessageReply();

        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public void LoadData(int PprSequence, string strSender, string strApprovePathSeq, string strSendSeq, string strStatus, bool bEdit)
        {
            lblSendSeq.Text = strSendSeq;
            lblApprovePathSeq.Text = strApprovePathSeq;
            lblRefSeq.Text = PprSequence.ToString();

            DataSet ds = pprBLL.GetPrePurchaseRequest(PprSequence);
            DataRowCollection drc = ds.Tables[0].Rows;

            if (drc.Count > 0)
            {
                lblFinBgmYear.Text = drc[0]["BGM_YEAR"].ToString();
                lblFinBgmProjOperDate.Text = string.Format("{0:dd/MM/yyyy}", drc[0]["CREATED_WHEN"]);

                lblPurchaseTypeName.Text = drc[0]["ICM_PC_TYPE_NAME"].ToString();
                lblPurchaseName.Text = drc[0]["ICM_PPR_NAME"].ToString();

                lblReason.Text = drc[0]["ICM_PPR_REASON"].ToString();
                lblForName.Text = drc[0]["ICM_PPR_FOR_NAME"].ToString();

                lblDuration.Text = drc[0]["REQUIRE_DATE"].ToString();
                lblAllBudget.Text = Convert.ToDouble(drc[0]["BGM_ALL_BUDGET"]).ToString("###,###,##0.00");
                lblRemainBudget.Text = Convert.ToDouble(drc[0]["BGM_REMAIN_BUDGET"]).ToString("###,###,##0.00");
            }

            LoadSenderInfo(strSender);
            LoadGridSubItem(PprSequence);
            LoadCommittee(PprSequence);
            

            //LoadSenderInfo(operInfo.emp_seq.ToString());
            //LoadFinProjectExpense(strBgmProjOperSeq, operInfo.bgm_proj_seq.ToString());

            //IList<BGM_MAS_Option.M_BGM_MAS_Option> optionInfoList = op.GetListFromBgmProjSeq("3", operInfo.bgm_proj_seq.ToString());// HardCode
            //Repeater2.DataSource = optionInfoList;
            //Repeater2.DataBind();

            //IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson> personInfoList = poper.GetFull(strBgmProjOperSeq);
            //Repeater3.DataSource = personInfoList;
            //Repeater3.DataBind();

            LoadDDLEmpSeq();
            bool bEnable = strStatus == "2";
            //cmdApprove.Enabled = !bEnable;
            //cmdSendBack.Enabled = !bEnable;
            //PanelOption.Visible = true;
            //PanelApprove.Visible = false;
            //PanelSendTo.Visible = false;
            PanelSendBack.Visible = false;
            PanelSend.Visible = false;
            txtRemark.Text = "";
        }
        protected void LoadGridSubItem(int PprSequence)
        {
            DataSet ds = pprBLL.GetPrePurchaseRequestItems(null, PprSequence);

            Repeater1.DataSource = ds;
            Repeater1.DataBind();
        }
        protected void LoadSenderInfo(string strEmpSeq)
        {
            DataTable dtb = emplist.GetInfo(Convert.ToInt32(strEmpSeq));

            if (dtb.Rows.Count > 0)
            {
                lblEmpSeq.Text = strEmpSeq;
                lblEmpName.Text = dtb.Rows[0]["full_name"].ToString();
                lblPosName.Text = dtb.Rows[0]["pos_name"].ToString();
                lblClassName.Text = dtb.Rows[0]["class_name"].ToString();
                lblJobsiteName.Text = dtb.Rows[0]["job_site_name"].ToString();
            }
        }
        protected void LoadDDLEmpSeq()
        {
            ddlApprover.DataSource = emplist.ListEmployeeByType("('1', '2', '3')", "");
            ddlApprover.DataBind();
        }
        protected void LoadEmpInfo(string strEmpSeq)
        {
            DataTable dtb = emplist.GetInfo(Convert.ToInt32(strEmpSeq));

            lblApproverEmpSeq.Text = dtb.Rows[0]["sequence"].ToString();
            lblApproverName.Text = dtb.Rows[0]["full_name"].ToString();
            lblApproverPosName.Text = dtb.Rows[0]["pos_name"].ToString();
            lblApproverClassName.Text = dtb.Rows[0]["class_name"].ToString();
            lblApproverExecPosName.Text = dtb.Rows[0]["exec_pos_name"].ToString();
            lblApproverJobsiteName.Text = dtb.Rows[0]["job_site_name"].ToString();
        }
        protected void LoadCommittee(int PprSeq)
        {
            DataSet ds = pprBLL.GetPrePurchaseRequestCommittee(null, PprSeq);
            Repeater4.DataSource = ds;
            Repeater4.DataBind();
        }

        public void cmdApprove_Click(object sender, EventArgs e)
        {
            //string strNextSeqNo = send.GetNextStepNo(lblApprovePathSeq.Text, lbl);

            //if (strNextSeqNo == "0")
            //{
            //    PanelApprove.Visible = true;
            //    PanelSendTo.Visible = false;
            //    lblMode.Text = "A";
            //}
            //else
            //{
            //    DataTable dtb = send.GetCurrentApprover(Session["EmpSeq"].ToString()
            //        , "icm_pre_purchase_request"
            //        , Convert.ToInt32(strNextSeqNo));

            //    if (dtb != null)
            //    {
            //        if (dtb.Rows.Count > 0)
            //        {
            //            lblNewApprovePathSeq.Text = dtb.Rows[0]["approve_path_seq"].ToString();
            //            LoadEmpInfo(dtb.Rows[0]["emp_seq"].ToString());
            //        }
            //    }

            //    PanelApprove.Visible = false;
            //    PanelSendTo.Visible = true;
            //    lblMode.Text = "F";
            //}

            //PanelSendBack.Visible = false;
            //// button
            //PanelOption.Visible = false;
            //PanelSend.Visible = true;
        }

        protected void cmdSendBack_Click(object sender, EventArgs e)
        {

        }

        private bool directApprove = false;
        public string Approve(string remark)
        {
            cmdApprove_Click(new Object(), new EventArgs());
            txtRemark.Text = remark;
            return cmdSendClick();
        }

        public void cmdSend_Click(object sender, EventArgs e)
        {
            cmdSendClick();
        }

        public string cmdSendClick()
        {
            try
            {
                int nEmpSeqLogin = SsMng.EmpSeqI;
                BGM_ProjectOperation.M_BGM_ProjectOperation operInfo = new BGM_ProjectOperation.M_BGM_ProjectOperation();
                ESS.MODEL.M_MessageSend info = new ESS.MODEL.M_MessageSend();
                ESS.MODEL.M_MessageReply replyInfo = new ESS.MODEL.M_MessageReply();

                // By Aek 2014-07-29
                // remark: in forwarding FromEmpSeq should be the previous emp_seq in message_send
                // string strFromEmpSeq = Session["EmpSeq"].ToString();
                var messageSendPrev = send.GetFull(null, null, null, null, null, null, null, lblSendSeq.Text)[0];
                string strFromEmpSeq = messageSendPrev.to_emp_seq.ToString();
                string strFromPosSeq = messageSendPrev.to_pos_seq.ToString();
                
                int nFromEmpSeq = Convert.ToInt32(strFromEmpSeq);
                int nFromPosSeq = Convert.ToInt32(strFromPosSeq);

                Nullable<int> nToEmpSeq = null;
                Nullable<int> nToPosSeq = null;
                Nullable<int> nWodEmpSeq = nEmpSeqLogin == nFromEmpSeq ? (int?)null : nEmpSeqLogin;
                
                bool bLeaf = true;
                string strSendSeq = lblSendSeq.Text;

                while (bLeaf)
                {
                    ESS.MODEL.M_MessageSend sendInfo = send.GetInfo(strSendSeq);
                    string strFromSendSeq = sendInfo.from_send_seq.ToString();

                    if (string.IsNullOrEmpty(strFromSendSeq))
                    {
                        bLeaf = false;
                        nToEmpSeq = sendInfo.from_emp_seq;
                        nToPosSeq = send.GetPosSeqFromEmpSeq(Convert.ToString(nToEmpSeq));
                    }

                    strSendSeq = strFromSendSeq;
                }

                switch (lblMode.Text)
                {
                    case "A":
                        pprBLL.ChangeStatus(Int32.Parse(lblRefSeq.Text)
                            , Int32.Parse(Session["EmpSeq"].ToString())
                            , SystemInfo._ApproveRecordStatus);

                        //operInfo.bgm_proj_oper_seq = Convert.ToInt32(lblBgmProjOperSeq.Text);
                        //operInfo.record_status = "A";
                        //operInfo.updated_by = nEmpSeq;
                        //operInfo.updated_when = DateTime.Now;
                        //if (!oper.ChangeStatus(operInfo))
                        //{
                        //    main.MessageAlert(Page, "ไม่สามารถอนุมัติได้ เนื่องจากจำนวนเงินเกินกว่าที่ได้รับจัดสรร");
                        //    return;
                        //}

                        //IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> expListInfo = poexp.GetFull(lblBgmProjOperSeq.Text, null, null);
                        //for (int i = 0; i < expListInfo.Count; i++)
                        //{
                        //    BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense expInfo = expListInfo[i];
                        //    BGM_ProjectOperationReport.M_BGM_ProjectOperationReport reportInfo = new BGM_ProjectOperationReport.M_BGM_ProjectOperationReport();
                        //    reportInfo.bgm_proj_oper_exp_seq = expInfo.bgm_proj_oper_exp_seq;
                        //    reportInfo.used_amount = expInfo.bath_amount;
                        //    reportInfo.cal_amount = expInfo.bath_amount;
                        //    reportInfo.rpt_type = 1;//เหมือนจัดสรร
                        //    reportInfo.created_by = nEmpSeq;
                        //    reportInfo.created_when = DateTime.Now;
                        //    //poreport.Insert(reportInfo);

                        //    BGM_ProjectReport.M_BGM_ProjectReport pjreportInfo = new BGM_ProjectReport.M_BGM_ProjectReport();
                        //    pjreportInfo.bgm_proj_exp_seq = expInfo.bgm_proj_exp_seq;
                        //    pjreportInfo.used_amount = expInfo.bath_amount;
                        //    pjreportInfo.cal_amount = -expInfo.bath_amount;
                        //    pjreportInfo.rpt_type = 4;//เหมือนกันเงิน
                        //    pjreportInfo.created_by = nEmpSeq;
                        //    pjreportInfo.created_when = DateTime.Now;
                        //    //pjreport.Insert(pjreportInfo);
                        //}

                        replyInfo.reply_date = DateTime.Today;
                        replyInfo.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                        replyInfo.reply_text = "อนุมัติให้ดำเนินโครงการได้ : " + lblPurchaseName.Text;
                        replyInfo.from_emp_seq = nFromEmpSeq;
                        replyInfo.from_pos_seq = nFromPosSeq;
                        replyInfo.to_emp_seq = nToEmpSeq;
                        replyInfo.to_pos_seq = nToPosSeq;
                        replyInfo.wod_emp_seq = nWodEmpSeq;
                        replyInfo.from_send_seq = Convert.ToInt32(lblSendSeq.Text);
                        replyInfo.message_status = "0";
                        replyInfo.created_by = nEmpSeqLogin;
                        replyInfo.created_when = DateTime.Now;
                        reply.Insert(replyInfo);

                        info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                        info.message_status = "2";
                        info.wod_emp_seq = nWodEmpSeq;
                        info.updated_by = nEmpSeqLogin;
                        info.updated_when = DateTime.Now;
                        send.UpdateMessageStatus(info);
                        break;
                    case "F":
                        //operInfo.bgm_proj_oper_seq = Convert.ToInt32(lblBgmProjOperSeq.Text);
                        //operInfo.record_status = "P";
                        //operInfo.updated_by = nEmpSeq;
                        //operInfo.updated_when = DateTime.Now;
                        //if (!oper.ChangeStatus(operInfo))
                        //{
                        //    main.MessageAlert(Page, "ไม่สามารถส่งต่อได้ เนื่องจากจำนวนเงินเกินกว่าที่ได้รับจัดสรร");
                        //    return;
                        //}

                        info.send_date = DateTime.Today;
                        info.ref_seq = main.ConvertNullInt(lblRefSeq.Text);
                        info.ref_type = "bgm_project_operation";
                        info.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                        info.send_text = "ขออนุมัติจัดซื้อ/จ้าง : " + lblPurchaseName.Text;
                        info.from_emp_seq = nFromEmpSeq;
                        info.from_pos_seq = nFromPosSeq;
                        info.to_emp_seq = main.ConvertNullInt(lblApproverEmpSeq.Text);
                        info.to_pos_seq = nToPosSeq;
                        info.from_send_seq = main.ConvertNullInt(lblSendSeq.Text);
                        info.remarks = null;
                        info.message_status = "0";
                        info.approve_path_seq = main.ConvertNullInt(lblNewApprovePathSeq.Text);
                        info.created_by = nEmpSeqLogin;
                        info.created_when = DateTime.Now;
                        send.Insert(info);

                        info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                        info.message_status = "2";
                        info.updated_by = nEmpSeqLogin;
                        info.updated_when = DateTime.Now;
                        send.UpdateMessageStatus(info);
                        break;
                    case "B":
                        //operInfo.bgm_proj_oper_seq = Convert.ToInt32(lblBgmProjOperSeq.Text);
                        //operInfo.record_status = "R";
                        //operInfo.updated_by = nEmpSeq;
                        //operInfo.updated_when = DateTime.Now;
                        //oper.ChangeStatus(operInfo);

                        replyInfo.reply_date = DateTime.Today;
                        replyInfo.ref_no = send.GetRefNoOfSendSeq(Convert.ToInt32(lblSendSeq.Text));
                        replyInfo.reply_text = "ส่งกลับมาเพื่อแก้ไข : " + lblPurchaseName.Text;
                        replyInfo.from_emp_seq = nFromEmpSeq;
                        replyInfo.from_pos_seq = nFromPosSeq;
                        replyInfo.to_emp_seq = nToEmpSeq;
                        replyInfo.to_pos_seq = nToPosSeq;
                        replyInfo.wod_emp_seq = nWodEmpSeq;
                        replyInfo.from_send_seq = Convert.ToInt32(lblSendSeq.Text);
                        replyInfo.remarks = txtRemark.Text;
                        replyInfo.message_status = "0";
                        replyInfo.created_by = nEmpSeqLogin;
                        replyInfo.created_when = DateTime.Now;
                        reply.Insert(replyInfo);

                        info.send_seq = Convert.ToInt32(lblSendSeq.Text);
                        info.message_status = "2";
                        info.wod_emp_seq = nWodEmpSeq;
                        info.updated_by = nEmpSeqLogin;
                        info.updated_when = DateTime.Now;

                        pprBLL.ChangeStatus(Int32.Parse(lblRefSeq.Text)
                            , Int32.Parse(Session["EmpSeq"].ToString())
                            , SystemInfo._ProcessRecordStatus);
                        break;
                }

                ((TaskListsPopUp) Page).cmdViewRequest_Click(null, null);
            }
            catch (Exception ex)
            {
                string errorStr = ex.Message + " " + ex.InnerException;
                if (!directApprove) main.MessageAlert(Page, errorStr);
                return errorStr;
            }
            return "";
        }

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            PanelApprove.Visible = false;
            PanelSendTo.Visible = false;
            PanelSendBack.Visible = false;
            // button
            PanelOption.Visible = true;
            PanelSend.Visible = false;
        }

        protected void Grid_SubItem_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {

        }

        protected void Grid_SubItem_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {

        }
    }
}